<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑文章</title>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        body{font-family: system-ui, -apple-system, Segoe UI, Roboto, "Helvetica Neue", Arial; background:#f8fafc;}
        .container{max-width: 860px;margin:40px auto;padding:20px;background:#fff;border:1px solid #e5e7eb;border-radius:12px;box-shadow:0 6px 16px rgba(0,0,0,.06)}
        h2{margin-bottom:16px;}
        .form-group{margin-bottom:12px;}
        label{display:block;margin-bottom:6px;color:#374151;font-size:14px}
        input,textarea{width:100%;padding:10px;border:1px solid #d1d5db;border-radius:8px;background:#f9fafb}
        textarea{min-height:160px}
        .row{display:grid;grid-template-columns:1fr 1fr;gap:12px}
        .actions{display:flex;gap:10px;margin-top:16px}
        .btn{padding:10px 16px;border-radius:8px;border:1px solid #d1d5db;background:#f9fafb;cursor:pointer}
        .btn-primary{background:#2563eb;color:#fff;border-color:#2563eb}
        .btn-secondary{background:#fff}
        .hint{color:#6b7280;margin-top:10px}
    </style>
    <script>
        const PROJECT_NAME = '';
        function backToList(){ window.location.href = 'articles'; }
        function q(name){ const u = new URL(window.location.href); return u.searchParams.get(name); }
        function draftKey(id){ return 'article-edit-draft-'+id; }
        function saveDraft(){
            const id = q('id');
            const data = collectForm();
            localStorage.setItem(draftKey(id), JSON.stringify(data));
            alert('草稿已保存到本地');
        }
        function collectForm(){
            return {
                id: q('id'),
                title: document.getElementById('title').value || '',
                tags: document.getElementById('tags').value || '',
                categoryId: document.getElementById('categoryId').value || '',
                authorId: document.getElementById('authorId').value || '',
                content: document.getElementById('content').value || ''
            };
        }
        async function loadArticle(){
            const id = q('id');
            if(!id){ alert('缺少文章ID'); return; }
            try{
                const res = await fetch('articles/get?id='+encodeURIComponent(id));
                const txt = await res.text();
                const json = JSON.parse(txt);
                if(json && json.success && json.data){
                    const d = json.data;
                    document.getElementById('title').value = d.title || '';
                    document.getElementById('tags').value = d.tags || '';
                    document.getElementById('categoryId').value = d.categoryId || '';
                    document.getElementById('authorId').value = d.authorId || '';
                    document.getElementById('content').value = d.content || '';
                    // 合并草稿（若存在）
                    const cache = localStorage.getItem(draftKey(id));
                    if(cache){
                        try{
                            const c = JSON.parse(cache);
                            if(c.title) document.getElementById('title').value = c.title;
                            if(c.tags) document.getElementById('tags').value = c.tags;
                            if(c.categoryId) document.getElementById('categoryId').value = c.categoryId;
                            if(c.authorId) document.getElementById('authorId').value = c.authorId;
                            if(c.content) document.getElementById('content').value = c.content;
                        }catch(_){}
                    }
                } else {
                    alert('加载失败');
                }
            }catch(err){ alert('网络错误: '+err.message); }
        }
        async function updateArticle(e){
            e && e.preventDefault();
            const data = collectForm();
            const fd = new FormData();
            fd.append('id', data.id);
            fd.append('title', data.title);
            fd.append('tags', data.tags);
            fd.append('categoryId', data.categoryId);
            fd.append('authorId', data.authorId);
            fd.append('content', data.content);
            try{
                const res = await fetch('articles/update', { method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body: fd });
                const txt = await res.text(); let json={}; try{ json = JSON.parse(txt);}catch(_){json={};}
                if(res.ok && json.success){ alert('更新成功'); localStorage.removeItem(draftKey(data.id)); backToList(); }
                else { alert('更新失败: '+(txt||res.status)); }
            }catch(err){ alert('网络错误: '+err.message); }
        }
        window.addEventListener('DOMContentLoaded', function(){
            loadArticle();
            document.getElementById('editForm').addEventListener('submit', updateArticle);
        });
    </script>
    </head>
<body>
<div class="container">
    <h2><i class="fa fa-pencil"></i> 编辑文章</h2>
    <form id="editForm">
        <div class="form-group">
            <label for="title">标题</label>
            <input id="title" name="title" required placeholder="请输入文章标题" />
        </div>
        <div class="form-group">
            <label for="tags">标签（用逗号分隔）</label>
            <input id="tags" name="tags" placeholder="示例：Java,Web,教程" />
        </div>
        <div class="row">
            <div class="form-group">
                <label for="categoryId">分类ID（可选）</label>
                <input id="categoryId" name="categoryId" type="number" min="1" placeholder="例如：1" />
            </div>
            <div class="form-group">
                <label for="authorId">作者ID（可选）</label>
                <input id="authorId" name="authorId" type="number" min="1" placeholder="例如：1" />
            </div>
        </div>
        <div class="form-group">
            <label for="content">内容</label>
            <textarea id="content" name="content" required placeholder="支持HTML片段，例如：<p>正文内容</p>"></textarea>
        </div>
        <div class="actions">
            <button type="button" class="btn" onclick="saveDraft()">保存草稿</button>
            <button type="submit" class="btn btn-primary">保存并发布更新</button>
            <button type="button" class="btn btn-secondary" onclick="backToList()">返回列表</button>
        </div>
    </form>
    <p class="hint">提示：保存草稿仅保存在浏览器本地。</p>
</div>
</body>
</html>